package com.tianqu.tms.www.car.controller;

import java.util.ArrayList;
import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.dto.MarketCarInfoDto;
import com.tianqu.tms.dto.MarketCarServiceDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.MarketCarGateInfo;
import com.tianqu.tms.entity.MarketCarService;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;
import com.tianqu.tms.www.car.viewhelper.CarPendingLiftViewHelper;

/**
 * @author mufeiyu
 * 库存取消 - 信息查看 controller
 */
public class CarStockCancleConfirmController extends TmsController {
	private Logger logger = Logger.getLogger(CarStockCancleConfirmController.class);
	public final static int CARCOLORITEMID = 105;
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();		
		
		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarPendingLiftViewHelper viewhelper = new CarPendingLiftViewHelper();
			CarPendingLiftActionForm form = (CarPendingLiftActionForm)uc.getInputForm();
			String vin = form.getVin();
			String id = form.getId();
			String licensePlate = form.getLicensePlate();
			
			Car car = Car.getInstance();
			List<MarketCarInfoDto> list = new ArrayList<MarketCarInfoDto>();
			if(!StringUtil.isNullOrBlank(licensePlate)){
				list = car.findCarList(licensePlate, 2);
			}else if(!StringUtil.isNullOrBlank(vin)){
				list = car.findCarList(vin, 1);
			}else if(!StringUtil.isNullOrBlank(id)){
				list = car.findCarList(id, 3);
			}
			
//			// 缴费金额，如果系统功能配置表（tms_configure）获取参数名为“isAutoPayForRegister”的值为“1：不开通”，那么缴费金额就不显示，
//			// 否则显示；值为关联的库存车辆业务信息表（tms_market_car_service）的
//			// 流程表缴费（checkPrice）+交易票缴费（transferPrice），如果值为”0“，那么页面显示”未缴费“，否则正常显示值
//			viewhelper.setIsAutoPayForRegister(Registry.getConfigFromDb(TmsConstants.ISAUTOPAYFORREGISTER));
//			if(list.size() > 0 && !"1".equals(viewhelper.getIsAutoPayForRegister())){
//				MarketCarInfoDto infoDto = list.get(0);
//				MarketCarServiceDto dto = car.findMarketCarService(infoDto.getSerial());
//				// 缴费金额
//				viewhelper.setPayment(String.valueOf(dto.getCheckPrice()+dto.getTransferPrice()));
//			}
			 
			//
			if(list.size() > 1){
				int i = 0;
				if (list.size() > 0 && list != null) {
					for (MarketCarInfoDto dto : list) {
						dto.setNum(++i);
						if(i%2 == 0) dto.setCssFlag(2); 
						else dto.setCssFlag(1);						
					}
				}
				viewhelper.setConfirmFlag(3);
				viewhelper.setMarkCarInfoDtoList(list);
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			}else if(list.size() == 1){//找到一条
				//modify by huangwei.
				//3）预缴金额，如果关联的库存车辆业务信息表（tms_market_car_service）的是否缴费（checkPrice）为“0：未缴费”，那么显示“未缴费”，如果为“1：缴费但未使用”，那么显示																	
				//库存车辆业务信息表（tms_market_car_service）的缴费金额（transferPrice），如果为“2：缴费已使用”，那么显示“缴费并已使用”	
				MarketCarInfoDto infoDto = list.get(0);
				MarketCarServiceDto dto = car.findMarketCarService(infoDto.getSerial());
				MarketCarService carService = MarketCarService.getInstance();
				MarketCarService marketCarService =  carService.findCarServiceInfoBySerial(infoDto.getSerial());
				viewhelper.setCheckPrice(marketCarService.getCheckPrice());
				viewhelper.setPayment(String.valueOf(dto.getTransferPrice()));
				//
				viewhelper.setConfirmFlag(2);
				setDetailInfo(list.get(0),viewhelper);
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			}else{//没有找到数据
				viewhelper.setConfirmFlag(1);
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			}
			 			
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}

	
	private void setDetailInfo(MarketCarInfoDto car,CarPendingLiftViewHelper viewhelper) throws TmsDaoException{
		//出入库数据
		MarketCarGateInfo marketCarGateInfo = MarketCarGateInfo.getInstance();
		//会员数据
		Member member = Member.getInstance();
		//字典信息
		Codes code = Codes.getInstance();

		if(!StringUtil.isNullOrBlank(car.getSerial())){
			member = member.findCarScoreByMemberId(String.valueOf(car.getMemberId()));
			//车辆编号
			viewhelper.setSerial(car.getSerial());
			viewhelper.setBasicCarId(car.getSerial());
			//车牌号码
			viewhelper.setLicensePlate(car.getLicensePlate());
			//车架号
			viewhelper.setVin(car.getVin());
			//车辆名称
			viewhelper.setCarName(car.getCarName());
			//车身颜色
			viewhelper.setCarColor(code.getItemValueByItemIdAndItemCode(CARCOLORITEMID,car.getColor()));
			//按钮显示flag
			viewhelper.setButtonFlag("true");
			//库存状态
			if(car.getRegisterStatus() == 1){
				viewhelper.setRegisterStatus("已入库");
			}else if(car.getRegisterStatus() == 2){
				viewhelper.setRegisterStatus("已出库");
			}else if (car.getRegisterStatus() == 3){			
				viewhelper.setRegisterStatus("过期");
			}else if (car.getRegisterStatus() == 4){
				viewhelper.setRegisterStatus("存档");
			}else if (car.getRegisterStatus() == 6){
				viewhelper.setRegisterStatus("登记");
			}			
			viewhelper.setRegisterStatusNum(car.getRegisterStatus());
			//商户ID
			viewhelper.setMemberId(car.getMemberId());				
			//车辆进出记录（最近5次）
			int i=1;
			List<MarketCarGateInfo> r = new ArrayList<MarketCarGateInfo>();
			for(MarketCarGateInfo info : marketCarGateInfo.findAllGateInfoBySerial(car.getSerial())){
			   if(i>5) break;
			   if(i%2 == 0) info.setCssFlag(2); 
			   else info.setCssFlag(1);
			   info.setNum(i);
			   i++;
			   r.add(info);
			}
			viewhelper.setGateInfoList(r);
			//商户信息	
			if(member != null){				
				// 当前库存量
				viewhelper.setUsedCarPort(member.getUsedCarPort());
				// 车位总数
				viewhelper.setCarPort(member.getCarPort());
				// 商户密码
				viewhelper.setPassword(member.getPassword());
				// 商户名称
				viewhelper.setMemName(member.getMemName());
			}
		}
	}
}
